﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;
using System.Data;
using Newtonsoft.Json.Linq;
using AspNet = System.Web.UI.WebControls;


namespace TCMSystem.admin
{
    public partial class role_module2 : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.CoreRoleModule;
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerEditWithButton(btnGroupUpdate);


            // 每页记录数
            Grid1.PageSize = TblMstConfigHelper.PageSize;
            BindGrid();
            // 默认选中第一个角色
            Grid1.SelectedRowIndex = 0;

            // 每页记录数
            Grid2.PageSize = TblMstConfigHelper.PageSize;
            BindGrid2();
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<TblMstRole>();
            q.Where("1").IsEqualTo("1");

            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, TblMstRole.Schema));

            TblMstRoleCollection items = q.ExecuteAsCollection<TblMstRoleCollection>();

            Grid1.DataSource = items;
            Grid1.DataBind();
        }

        private void BindGrid2()
        {
            TblMstMenuCollection items = new TblMstMenuCollection();

            int roleId = GetSelectedRoleId();
            if (roleId > 0)
            {
                SqlQuery q = new Select().From<TblMstMenu>();
                q.Where("1").IsEqualTo("1");

                // 名称不是AppModule.None
                q.And(TblMstMenu.NameColumn).IsNotEqualTo(ModuleTypeHelper.Module2String(ModuleType.None));

                // 在模块标题中搜索
                string searchText = ttbSearchUser.Text.Trim();
                if (!String.IsNullOrEmpty(searchText))
                {
                    q.And(TblMstMenu.TitleColumn).ContainsString(searchText);
                }

                // 排列
                q.OrderBys.Add(GetSortExpression(Grid2, TblMstMenu.Schema));

                items = q.ExecuteAsCollection<TblMstMenuCollection>();
            }
            else
            {
                Grid2.RecordCount = 0;
            }

            Grid2.DataSource = RoleModulePowerHelper.GetRoleModulePowers(roleId, items);
            Grid2.DataBind();
        }

        #endregion

        #region Private

        /// <summary>
        /// 获取选中的角色ID（没有则返回-1）
        /// </summary>
        /// <returns></returns>
        private int GetSelectedRoleId()
        {
            int roleId = -1;
            int rowIndex = Grid1.SelectedRowIndex;
            if (rowIndex >= 0)
            {
                roleId = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
            }
            return roleId;
        }

        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();

            // 默认选中第一个角色
            Grid1.SelectedRowIndexArray = new int[] { 0 };

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, ExtAspNet.GridRowClickEventArgs e)
        {
            BindGrid2();
        }

        #endregion

        #region Grid2 Events

        protected void Grid2_RowDataBound(object sender, ExtAspNet.GridRowEventArgs e)
        {
            AspNet.CheckBoxList ddlOthers = (AspNet.CheckBoxList)Grid2.Rows[e.RowIndex].FindControl("ddlOthers");

            RoleModulePower row = e.DataItem as RoleModulePower;
            string moduleName = row.Name;

            List<string> otherPowerNames = ModulePowerTypeHelper.GetModuleOtherPowerTypeDic(moduleName);

            foreach (string powerName in otherPowerNames)
            {
                // powerName = "ChangePassword" moduleName = "CoreUser"
                AspNet.ListItem item = new AspNet.ListItem();
                item.Value = powerName;
                item.Text = ModulePowerTypeHelper.GetTitle(moduleName, powerName);

                item.Selected = row.OtherPowers[powerName].Value<bool>();

                ddlOthers.Items.Add(item);
            }
        }

        protected void ttbSearchUser_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchUser.ShowTrigger1 = true;
            BindGrid2();
        }

        protected void ttbSearchUser_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchUser.Text = String.Empty;
            ttbSearchUser.ShowTrigger1 = false;
            BindGrid2();
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortColumnIndex = e.ColumnIndex;
            BindGrid2();
        }

        protected void btnGroupUpdate_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerEdit())
            {
                CheckPowerFailWithAlert();
                return;
            }


            int roleId = GetSelectedRoleId();

            // 首先从TblMstRolemodule表中删除所有记录
            TblMstRolemodule.Delete(TblMstRolemodule.RoleIdColumn.ColumnName, roleId);

            // 添加所有记录
            ExtAspNet.CheckBoxField canReadField = Grid2.FindColumn("CanRead") as ExtAspNet.CheckBoxField;


            TblMstRolemoduleCollection roleModules = new TblMstRolemoduleCollection();
            foreach (GridRow row in Grid2.Rows)
            {
                int rowIndex = row.RowIndex;

                object[] dataKeys = Grid2.DataKeys[rowIndex];
                // 当前行对应的模块ID
                int moduleId = Convert.ToInt32(dataKeys[0]);
                //string moduleName = dataKeys[1].ToString();

                bool canRead = canReadField.GetCheckedState(rowIndex);
                AspNet.CheckBoxList ddlOthers = (AspNet.CheckBoxList)Grid2.Rows[rowIndex].FindControl("ddlOthers");

                JObject otherPowerObj = new JObject();
                foreach (AspNet.ListItem item in ddlOthers.Items)
                {
                    if (item.Selected)
                    {
                        otherPowerObj.Add(item.Value, true);
                    }
                }

                if (canRead || otherPowerObj.Count > 0)
                {
                    TblMstRolemodule roleModule = new TblMstRolemodule();
                    roleModule.RoleId = roleId;
                    roleModule.ModuleId = moduleId;
                    roleModule.CanRead = canRead;
                    if (otherPowerObj.Count > 0)
                    {
                        roleModule.Others = otherPowerObj.ToString(Newtonsoft.Json.Formatting.None);
                    }
                    else
                    {
                        roleModule.Others = "";
                    }

                    roleModules.Add(roleModule);
                }
            }
            roleModules.BatchSave();

            // 更新缓存
            RoleModulePowerHelper.UpdateRoleModulePowerDic(roleId);


            Alert.ShowInTop("当前角色的模块权限更新成功！");
        }

        protected void btnSelectAll_Click(object sender, EventArgs e)
        {
            MenuButton mbtn = sender as MenuButton;
            if (mbtn == mbtnSelectAll)
            {
                SelectAll(true);
            }
            else if (mbtn == mbtnSelectAllSelected)
            {
                SelectAllSelected(true);
            }
            else if (mbtn == mbtnSelectAllCanRead)
            {
                SelectAllCheckBoxField("CanRead", true);
            }
        }

        protected void btnUnSelectAll_Click(object sender, EventArgs e)
        {
            MenuButton mbtn = sender as MenuButton;
            if (mbtn == mbtnUnSelectAll)
            {
                SelectAll(false);
            }
            else if (mbtn == mbtnUnSelectAllSelected)
            {
                SelectAllSelected(false);
            }
            else if (mbtn == mbtnUnSelectAllCanRead)
            {
                SelectAllCheckBoxField("CanRead", false);
            }
        }

        /// <summary>
        /// 修改某列复选框的状态
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="selected"></param>
        private void SelectAllCheckBoxField(string columnName, bool selected)
        {
            ExtAspNet.CheckBoxField canField = Grid2.FindColumn(columnName) as ExtAspNet.CheckBoxField;

            for (int i = 0; i < Grid2.Rows.Count; i++)
            {
                canField.SetCheckedState(i, selected);
            }
        }

        /// <summary>
        /// 修改选中行复选框的状态
        /// </summary>
        /// <param name="selected"></param>
        private void SelectAllSelected(bool selected)
        {
            int[] selectedIndexs = Grid2.SelectedRowIndexArray;
            for (int i = 0; i < selectedIndexs.Length; i++)
            {
                int rowIndex = selectedIndexs[i];

                SelectAllInRowIndex(rowIndex, selected);
            }

            Grid2.UpdateTemplateFields();
        }

        /// <summary>
        /// 修改全部复选框的状态
        /// </summary>
        /// <param name="selected"></param>
        private void SelectAll(bool selected)
        {
            for (int i = 0; i < Grid2.Rows.Count ; i++)
            {
                SelectAllInRowIndex(i, selected);
            }

            Grid2.UpdateTemplateFields();
        }

        /// <summary>
        /// 修改某行复选框的状态
        /// </summary>
        private void SelectAllInRowIndex(int rowIndex, bool selected)
        {
            ExtAspNet.CheckBoxField canReadField = Grid2.FindColumn("CanRead") as ExtAspNet.CheckBoxField;

            canReadField.SetCheckedState(rowIndex, selected);

            AspNet.CheckBoxList ddlOthers = (AspNet.CheckBoxList)Grid2.Rows[rowIndex].FindControl("ddlOthers");
            foreach (AspNet.ListItem item in ddlOthers.Items)
            {
                item.Selected = selected;
            }
        }

        #endregion

    }
}
